package com.github.mzule.fantasyslide;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;

/**
 * Created by CaoDongping on 9/7/16.
 */

class DefaultTransformer implements Transformer {
    private float maxTranslationX;
    private Component lastHoverView;

    DefaultTransformer(float maxTranslationX) {
        this.maxTranslationX = maxTranslationX;
    }

    @Override
    public void apply(ComponentContainer sideBar, Component itemView,
                      float touchY, float slideOffset, boolean isLeft) {
        boolean hovered = itemView.isPressed();
        double translationX;
        int centerY = itemView.getTop() + itemView.getHeight() / 2;
        double distance = Math.abs((double) touchY - (double) centerY);
        double scale = distance / sideBar.getHeight() * 3; // 距离中心点距离与 sideBar 的 1/3 对比
        if (isLeft) {
            translationX = Math.max(0, maxTranslationX - scale * maxTranslationX);
            if (hovered) {
                setSelectColor(itemView);
            }
            if (lastHoverView != null) {
                if (lastHoverView.getTop() > touchY || lastHoverView.getBottom() < touchY) {
                    setTextColor(lastHoverView);
                }
            }
            lastHoverView = itemView;
        } else {
            translationX = Math.min(0, maxTranslationX - scale * maxTranslationX);
        }
        itemView.setTranslationX((float) translationX * slideOffset);
    }

    private void setTextColor(Component itemView) {
        Text text;
        if (itemView instanceof DirectionalLayout) {
            DirectionalLayout layout = (DirectionalLayout) itemView;
            text = (Text) layout.getComponentAt(1);
        } else {
            text = (Text) itemView;
        }
        text.setTextColor(Color.WHITE);
    }

    private void setSelectColor(Component itemView) {
        Text text;
        if (itemView instanceof DirectionalLayout) {
            DirectionalLayout layout = (DirectionalLayout) itemView;
            text = (Text) layout.getComponentAt(1);
        } else {
            text = (Text) itemView;
        }
        text.setTextColor(Color.RED);
    }

}
